# ASR ONNX FFI 系统依赖安装脚本
# Microsoft Visual C++ Redistributable 2015-2022 自动安装

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "ASR ONNX FFI 系统依赖安装器" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# 检查管理员权限
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host "⚠️  需要管理员权限来安装系统组件" -ForegroundColor Yellow
    Write-Host "请右键点击此脚本，选择'以管理员身份运行'" -ForegroundColor Yellow
    Read-Host "按任意键退出"
    exit 1
}

Write-Host "✅ 管理员权限确认" -ForegroundColor Green
Write-Host ""

# 检查当前系统
Write-Host "🔍 检查系统信息..." -ForegroundColor Blue
$osInfo = Get-CimInstance Win32_OperatingSystem
Write-Host "   操作系统: $($osInfo.Caption)" -ForegroundColor Gray
Write-Host "   版本: $($osInfo.Version)" -ForegroundColor Gray
Write-Host "   架构: $($env:PROCESSOR_ARCHITECTURE)" -ForegroundColor Gray
Write-Host ""

# 检查现有的 VC++ Redistributable
Write-Host "🔍 检查现有的 Visual C++ Redistributable..." -ForegroundColor Blue

$vcRedistInstalled = $false
try {
    $regPath = "HKLM:\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64"
    if (Test-Path $regPath) {
        $version = Get-ItemProperty -Path $regPath -Name "Version" -ErrorAction SilentlyContinue
        if ($version) {
            Write-Host "   ✅ 找到已安装的版本: $($version.Version)" -ForegroundColor Green
            $vcRedistInstalled = $true
        }
    }
} catch {
    Write-Host "   ❌ 注册表检查失败" -ForegroundColor Red
}

if (-not $vcRedistInstalled) {
    Write-Host "   ❌ 未找到 Visual C++ Redistributable x64" -ForegroundColor Red
    Write-Host ""
    
    # 下载并安装
    $downloadUrl = "https://aka.ms/vs/17/release/vc_redist.x64.exe"
    $tempFile = "$env:TEMP\vc_redist.x64.exe"
    
    Write-Host "📥 下载 Microsoft Visual C++ Redistributable..." -ForegroundColor Blue
    Write-Host "   下载地址: $downloadUrl" -ForegroundColor Gray
    Write-Host "   保存位置: $tempFile" -ForegroundColor Gray
    
    try {
        # 使用 Invoke-WebRequest 下载
        $ProgressPreference = 'SilentlyContinue'
        Invoke-WebRequest -Uri $downloadUrl -OutFile $tempFile -UseBasicParsing
        Write-Host "   ✅ 下载完成" -ForegroundColor Green
        
        # 验证文件
        if (Test-Path $tempFile) {
            $fileSize = (Get-Item $tempFile).Length
            Write-Host "   文件大小: $([math]::Round($fileSize / 1MB, 2)) MB" -ForegroundColor Gray
            
            if ($fileSize -gt 1MB) {
                Write-Host ""
                Write-Host "🚀 安装 Visual C++ Redistributable..." -ForegroundColor Blue
                
                # 静默安装
                $installArgs = "/install", "/quiet", "/norestart"
                $process = Start-Process -FilePath $tempFile -ArgumentList $installArgs -Wait -PassThru
                
                if ($process.ExitCode -eq 0) {
                    Write-Host "   ✅ 安装成功!" -ForegroundColor Green
                } elseif ($process.ExitCode -eq 3010) {
                    Write-Host "   ✅ 安装成功 (需要重启)" -ForegroundColor Yellow
                } else {
                    Write-Host "   ❌ 安装失败，退出代码: $($process.ExitCode)" -ForegroundColor Red
                }
            } else {
                Write-Host "   ❌ 下载的文件太小，可能下载失败" -ForegroundColor Red
            }
        }
        
        # 清理临时文件
        if (Test-Path $tempFile) {
            Remove-Item $tempFile -ErrorAction SilentlyContinue
        }
        
    } catch {
        Write-Host "   ❌ 下载或安装失败: $($_.Exception.Message)" -ForegroundColor Red
        Write-Host ""
        Write-Host "📋 手动安装说明:" -ForegroundColor Yellow
        Write-Host "   1. 访问: https://aka.ms/vs/17/release/vc_redist.x64.exe" -ForegroundColor Gray
        Write-Host "   2. 下载并运行安装程序" -ForegroundColor Gray
        Write-Host "   3. 重启计算机" -ForegroundColor Gray
    }
} else {
    Write-Host "   ✅ Visual C++ Redistributable 已安装" -ForegroundColor Green
}

Write-Host ""
Write-Host "🔍 最终检查..." -ForegroundColor Blue

# 再次检查安装状态
$finalCheck = $false
try {
    $regPath = "HKLM:\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64"
    if (Test-Path $regPath) {
        $version = Get-ItemProperty -Path $regPath -Name "Version" -ErrorAction SilentlyContinue
        if ($version) {
            Write-Host "   ✅ Visual C++ Redistributable x64 已安装: $($version.Version)" -ForegroundColor Green
            $finalCheck = $true
        }
    }
} catch {
    Write-Host "   ❌ 无法验证安装状态" -ForegroundColor Red
}

Write-Host ""
if ($finalCheck) {
    Write-Host "🎉 系统依赖检查完成! 现在可以运行 ASR ONNX FFI 应用程序了。" -ForegroundColor Green
} else {
    Write-Host "⚠️  可能仍需要手动安装或重启系统。" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "按任意键退出..."
Read-Host
